package cn.taokuaidi.wangwang.client.reader;

import java.util.ArrayList;

import cn.taokuaidi.wangwang.client.model.ChartDO;
import cn.taokuaidi.wangwang.client.util.JSONUtil;

import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.DataReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;

public class ChartReader<C> implements DataReader<C, ListLoadResult<ModelData>> {

    public ListLoadResult read(C loadConfig, Object data) {

        JSONArray root = (JSONArray) JSONParser.parse((String) data);
        int size = root.size();
        ArrayList<ModelData> records = new ArrayList<ModelData>();
        for (int i = 0; i < size; i++) {
            JSONObject obj = (JSONObject) root.get(i);
            ChartDO model = new ChartDO();
            JSONUtil.setModelValue(obj, model, getChartType());
            records.add(model);
        }
        ListLoadResult retVal = new BaseListLoadResult(records);
        return retVal;
    }

    private ModelType getChartType() {
        ModelType modelType = new ModelType();
        modelType.addField("key");
        modelType.addField("name");
        modelType.addField("value");
        return modelType;
    }
}
